//
//  PAWebSocketManager.m
//  PilotSeries
//
//  Created by 黄立强 on 16/6/29.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PAWebSocketManager.h"
#import "SRWebSocket.h"


@interface PAWebSocketManager ()<SRWebSocketDelegate>


@end

@implementation PAWebSocketManager

+ (instancetype)sharedInstance {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

-(void) connectToWebSocketServer:(NSString *) url{
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    self.url = url;
    _webSocket.delegate = self;
    self.firstOpen = YES;
    [_webSocket open];
    DDLogInfo(@"connectToWebSocketServer: %@",url);
    
    
}

-(void) disconnect{
    self.firstOpen = NO;
    [_webSocket close];
}


- (void)reconnect;
{
    if ([UIApplication sharedApplication].applicationState !=UIApplicationStateActive){
        
        return;
    }
    if ( [PAAppContext sharedInstance].netStatus == AFNetworkReachabilityStatusNotReachable) {
        DDLogInfo(@"auto reconnectToWebSocketServer fail because of AFNetworkReachabilityStatusNotReachable!");
        return;
    }
    _webSocket.delegate = nil;
    [_webSocket close];
    self.firstOpen = NO;
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    _webSocket.delegate = self;
    
    [_webSocket open];
    DDLogInfo(@"reconnectToWebSocketServer: %@ reconnect !",_url);
    
}

-(BOOL)sendMsg:(id)data{
    
    if (self.webSocket.readyState ==SR_OPEN) {
        [_webSocket send:data];
        DDLogWarn(@"sendMsg:%@",data);
        return YES;
    }else{
        DDLogInfo(@"sendMsg fail,because of connection is down,please send again");
        if ([CRToastManager isShowingNotification]) {
            return NO;
        }
        [CRToastManager showNotificationWithMessage:@"sendMsg fail,because of connection is down,please try again" completionBlock:^{
            
        }];
        [self reconnect];
        return NO;
    }
    
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(NSString *)message{
    
//    DDLogWarn(@"didReceiveMessage :%@",message);
    NSDictionary *dic =  [message mj_JSONObject];
    if (dic==nil) {
        DDLogError(@"webSocketReceive NUll Message ");
        return;
    }
    
    [[PAAppContext sharedInstance] processData:dic];

    
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    DDLogDebug(@"webSocketDidOpen: %@ ",_url);
    if (self.firstOpen) {
      
        if ([self.firstOpenDelegate respondsToSelector:@selector(webSocketManagerFirstOpen:)]) {
            [self.firstOpenDelegate webSocketManagerFirstOpen:self];
            DDLogDebug(@"webSocketfirstOpenDelegate: %@ ",_url);
        }
        
    }
    if (self.connectTimer!=nil) {
        [self.connectTimer invalidate];
        self.connectTimer = nil;
    }
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    DDLogDebug(@"didFailWithError:%@",error);
        [self.connectTimer invalidate];
        self.connectTimer = nil ;
        [self reconnect];
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    DDLogDebug(@"didCloseWithCode:%ld",(long)code);
    [self.connectTimer invalidate];
     self.connectTimer = nil ;
    [self reconnect];
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    
//    LOG(@"webSocket didReceivePong :%@",[[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding])
}

// 心跳连接
-(void)longConnectToSocket{
    
    // 根据服务器要求发送固定格式的数据，假设为指令@"longConnect"，但是一般不会是这么简单的指令
    if ([UIApplication sharedApplication].applicationState ==UIApplicationStateActive) {
        if(self.webSocket.readyState ==SR_OPEN){
            [self.webSocket sendPing:[@"heart beart" dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
    }
    
    
}

@end
